import streamlit as st
import uuid
from config_manager import ConfigManager, GitAccount
from git_manager import GitManager
from security_manager import SecurityManager

st.set_page_config(
    page_title="白菜-Git多账号管理工具",
    page_icon="🔧",
    layout="wide"
)

@st.cache_resource
def get_managers():
    config_manager = ConfigManager()
    git_manager = GitManager()
    security_manager = SecurityManager()
    return config_manager, git_manager, security_manager

def main():
    st.title("🔧 白菜-Git多账号管理工具")
    
    config_manager, git_manager, security_manager = get_managers()
    
    if 'selected_account_id' not in st.session_state:
        st.session_state.selected_account_id = None
    
    current_name, current_email = git_manager.get_current_user_info()
    
    col1, col2 = st.columns([2, 1])
    
    with col2:
        st.subheader("当前Git配置")
        if current_name and current_email:
            st.success(f"**用户名:** {current_name}")
            st.success(f"**邮箱:** {current_email}")
        else:
            st.warning("未检测到Git全局配置")
    
    with col1:
        st.subheader("账号管理")
        
        tab1, tab2, tab3 = st.tabs(["账号列表", "添加账号", "设置"])
        
        with tab1:
            accounts = config_manager.get_all_accounts()
            
            if accounts:
                for account in accounts:
                    with st.container():
                        col_info, col_actions = st.columns([3, 1])
                        
                        with col_info:
                            is_current = (current_name == account.username and 
                                        current_email == account.email)
                            status_icon = "✅" if is_current else "⭕"
                            default_icon = "⭐" if account.is_default else ""
                            
                            st.write(f"{status_icon} {default_icon} **{account.name}**")
                            st.write(f"用户名: {account.username}")
                            st.write(f"邮箱: {account.email}")
                        
                        with col_actions:
                            if st.button(f"切换", key=f"switch_{account.id}"):
                                if git_manager.set_global_config(account):
                                    st.success(f"已切换到账号: {account.name}")
                                    st.rerun()
                                else:
                                    st.error("切换失败")
                            
                            if st.button(f"删除", key=f"delete_{account.id}"):
                                config_manager.delete_account(account.id)
                                st.success(f"已删除账号: {account.name}")
                                st.rerun()
                            
                            if st.button(f"设为默认", key=f"default_{account.id}"):
                                config_manager.set_default_account(account.id)
                                st.success(f"已设置 {account.name} 为默认账号")
                                st.rerun()
                        
                        st.divider()
            else:
                st.info("暂无配置的账号，请添加新账号")
        
        with tab2:
            st.subheader("添加新账号")
            
            with st.form("add_account_form"):
                account_name = st.text_input("账号名称", placeholder="例如: 工作账号")
                username = st.text_input("用户名", placeholder="Git用户名")
                email = st.text_input("邮箱", placeholder="Git邮箱地址")
                password = st.text_input("密码 (可选)", type="password", 
                                       placeholder="HTTP认证密码，可留空")
                is_default = st.checkbox("设为默认账号")
                
                submitted = st.form_submit_button("添加账号")
                
                if submitted:
                    if account_name and username and email:
                        account_id = str(uuid.uuid4())
                        encrypted_password = security_manager.encrypt_password(password) if password else ""
                        
                        new_account = GitAccount(
                            id=account_id,
                            name=account_name,
                            username=username,
                            email=email,
                            password_encrypted=encrypted_password,
                            is_default=is_default
                        )
                        
                        if config_manager.add_account(new_account):
                            st.success(f"账号 '{account_name}' 添加成功！")
                            st.rerun()
                        else:
                            st.error("账号添加失败，可能已存在相同ID的账号")
                    else:
                        st.error("请填写所有必填字段")
        
        with tab3:
            st.subheader("工具设置")
            
            col_backup, col_test = st.columns(2)
            
            with col_backup:
                st.write("**配置备份**")
                if st.button("备份当前Git配置"):
                    if git_manager.backup_config():
                        st.success("配置备份成功")
                    else:
                        st.error("配置备份失败")
                
                if st.button("恢复Git配置"):
                    if git_manager.restore_config():
                        st.success("配置恢复成功")
                        st.rerun()
                    else:
                        st.error("配置恢复失败")
            
            with col_test:
                st.write("**连接测试**")
                test_url = st.text_input("测试仓库URL (可选)", 
                                       placeholder="https://github.com/user/repo.git")
                
                if st.button("测试Git连接"):
                    if git_manager.test_git_connection(test_url if test_url else None):
                        st.success("Git连接测试成功")
                    else:
                        st.error("Git连接测试失败")
    
    st.sidebar.header("快速操作")
    
    accounts = config_manager.get_all_accounts()
    if accounts:
        st.sidebar.subheader("快速切换账号")
        account_names = [f"{acc.name} ({acc.username})" for acc in accounts]
        selected_idx = st.sidebar.selectbox("选择账号", range(len(accounts)), 
                                          format_func=lambda x: account_names[x])
        
        if st.sidebar.button("快速切换"):
            selected_account = accounts[selected_idx]
            if git_manager.set_global_config(selected_account):
                st.sidebar.success(f"已切换到: {selected_account.name}")
                st.rerun()
            else:
                st.sidebar.error("切换失败")
    
    st.sidebar.subheader("本地仓库配置")
    repo_path = st.sidebar.text_input("仓库路径", value=".", 
                                     placeholder="本地Git仓库路径")
    
    if git_manager.is_git_repo(repo_path):
        st.sidebar.success("✅ 检测到Git仓库")
        
        if accounts and st.sidebar.button("应用到本地仓库"):
            if st.session_state.get('selected_account_id'):
                account = config_manager.get_account(st.session_state.selected_account_id)
                if account and git_manager.set_local_config(account, repo_path):
                    st.sidebar.success("本地仓库配置成功")
                else:
                    st.sidebar.error("本地仓库配置失败")
    else:
        st.sidebar.warning("❌ 指定路径不是Git仓库")

if __name__ == "__main__":
    main()